package com.xmutca.core.websocket.handler;

import com.xmutca.core.websocket.ChannelFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class CloseWebSocketFrameHandler extends SimpleChannelInboundHandler<CloseWebSocketFrame> {

	private final static Logger logger = LoggerFactory.getLogger(CloseWebSocketFrameHandler.class);

	private ChannelFactory channelFactory;

	private WebSocketEventHandler webSocketEventHandler;

	private TextWebSocketFrameHandler textWebSocketFrameHandler;

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, CloseWebSocketFrame frame) throws Exception {
		//移除session
		String userId = channelFactory.removeSession(ctx.channel());

		//关闭握手状态
		channelFactory.closeHandShaker(ctx, frame);

		if (webSocketEventHandler == null) {
			webSocketEventHandler = new WebSocketEventHandler();
		}

		//处理关闭事件
		webSocketEventHandler.open(textWebSocketFrameHandler, userId);
		logger.debug("用户：{} -> 离开了WebSocket服务器", userId);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		//cause.printStackTrace();
		String userId = channelFactory.getUserId(ctx.channel());
		logger.debug("用户：{} -> 离开WebSocket服务器过程中发生了异常", userId);

		//移除session
		channelFactory.removeSession(ctx.channel());
		ctx.close();
	}

	public void setChannelFactory(ChannelFactory channelFactory) {
		this.channelFactory = channelFactory;
	}

	public void setWebSocketEventHandler(WebSocketEventHandler webSocketEventHandler) {
		this.webSocketEventHandler = webSocketEventHandler;
	}

	public void setTextWebSocketFrameHandler(TextWebSocketFrameHandler textWebSocketFrameHandler) {
		this.textWebSocketFrameHandler = textWebSocketFrameHandler;
	}
}